use std::char::from_digit;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    assert!(
        to_base >= 2 && to_base <= 16,
        "to_base must be between 2 and 16"
    );
    // 将输入字符串分割为数字部分和进制部分
    let (from_num_str, from_base_str) = num_str[..num_str.len() - 1]
        .split_once('(')
        .expect("Invalid num_str");

    // 将原进制字符串解析为 u32 类型
    let from_base = from_base_str.parse().expect("Invalid from base");
    assert!(
        from_base >= 2 && from_base <= 16,
        "from_base must be between 2 and 16"
    );
    // 将原数字字符串从指定进制转换为 u32
    let mut from_num = u32::from_str_radix(from_num_str, from_base).expect("Invalid from num");

    // 将原数字从指定进制转换为目标进制
    let mut to_num = vec![];
    while from_num > 0 {
        // 计算当前位的值
        let part = from_num % to_base;
        // 更新原数字以便于下一位计算
        from_num = from_num / to_base;
        // 将当前位转换为对应字符
        to_num.push(from_digit(part, to_base).unwrap());
    }
    // 反转向量并将其转换为字符串
    to_num.into_iter().rev().collect()
}
